import os,sys
import socket
import fcntl, struct
from xml.etree import ElementTree

##########################fork begin############################################
#try to get work dir
workdir = sys.argv[0][ 0:sys.argv[0].rfind('/') ]
appname = sys.argv[0][ (sys.argv[0].rfind('/')+1) : len(sys.argv[0]) ]
pidpath = workdir + '/' + appname + '.pid'
logpath = workdir + '/' + appname + '.log'

sys.stdout=open(logpath, 'w')

try:
    filePid = open(pidpath, 'rb')
    print 'broadcastserver is running', filePid.read()
    filePid.close()
    exit(0)

except IOError:
    pass

filePid = open(pidpath, 'wb')
filePid.write(str(os.getpid()))
filePid.close()
#####################end fork###################################################

host=''
port=10000

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
s.bind((host,port))


def getNetDevInfo(ifname = 'eth0'):  
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);  
    
    inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname));  
    ip = socket.inet_ntoa(inet[20:24]);  
    
    inet = fcntl.ioctl(s.fileno(), 0x8913, struct.pack('256s', ifname));  
    
    flag = struct.unpack_from('h', inet, 16)
    
    return (ifname, bool(flag[0]&0x40), ip) 

def getAllNetDevInfo():
    info = []
    
    netdev = open('/proc/net/dev')
    netdev.readline()
    netdev.readline()
    for l in netdev.readlines():
        n0 = l.split()[0]
        n = n0[:len(n0)-1]
    
        #try ioctl
        try:
            it = getNetDevInfo(n)
            if it:
                info.append(it)
                
        except IOError,e:
            print "failed:try to get "+n+" info------>", e
    
    return info
    
while 1:
    try:
        data,addr=s.recvfrom(1024)
        
        print "got data from:",addr, " data:"
        print data
        
        r = ElementTree.fromstring(data)
        req = r.findall('./request')[0]
        
        if '/conf/machine/net/' == req.get('uri') and 'GET' == req.get('method'):
            root = ElementTree.Element('hdp')
            node = root

            node = ElementTree.SubElement(node, 'response', {'method':'GET', 'uri':'/conf/machine/net/'})
            
            node = ElementTree.SubElement(node , 'conf')
            node = ElementTree.SubElement(node, 'machine')
            node = ElementTree.SubElement(node, 'net')
            
            for dev in getAllNetDevInfo():
                if dev[1] and 'lo' != dev[0]:
                    n0 = ElementTree.SubElement(node, 'dev', {'name':dev[0]})
                    n1 = ElementTree.SubElement(n0, 'ip')
                    n1.text = dev[2]
        
            print ElementTree.tostring(root, 'utf8', 'xml')
            s.sendto(ElementTree.tostring(root, 'utf8', 'xml'), addr)
            
    except KeyboardInterrupt:
        raise
    except IOError,e:
        print e.strerror
        pass